package com.jsbj.framework.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
//映射webSocket服务路径
@ServerEndpoint("/api/QDWebSocket/{randomParam}")
@Component
public class QDWebSocket {

    private String randomParam;

    private Session session;

    private static Map<String, QDWebSocket> client = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("randomParam") String randomParam, Session session){
        log.info("新连接：{}",randomParam);
        if (!isEmpty(randomParam)){
            this.randomParam = randomParam;
            this.session = session;
            client.put(randomParam+"_"+session.getId(), this);
            log.info("现在连接的客户编码为：" + randomParam);
        }
    }

    /**
     * 关闭时执行
     */
    @OnClose
    public void onClose() {
        client.remove(randomParam+"_"+session.getId());
        log.info("连接：{} 关闭", this.randomParam+"_"+session.getId());
    }

    /**
     * 收到消息时执行
     * @param message
     * @param session
     */
    @OnMessage(maxMessageSize = 3000000)
    public void onMessage(String message, Session session) {
//        log.info("收到用户{}的消息:{}", this.randomParam, message);
        //回复用户
        for (String key : client.keySet()) {
            if (key.startsWith(randomParam)) {
                client.get(key).session.getAsyncRemote().sendText(message);
            }
        }
//        session.getAsyncRemote().sendText(message);
    }

    /**
     * 连接错误时执行
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("用户id为：{}的连接发送错误", this.randomParam);
        error.printStackTrace();
    }

    /**
     * 消息点对点推送
     * @param message
     */
    public void sendMessageToUser(String userId,String message) {

        QDWebSocket session = client.get(userId);
        if (session != null) {
            if (session.session.isOpen()) {
//                session.session.getAsyncRemote().sendText("收到 " + userId + " 的消息:" + message);
                session.session.getAsyncRemote().sendText("收到一条待办信息:" + message);
            } else {
                log.info("用户session关闭");
            }
        } else {
            log.info("用户session不存在");
        }
    }

    private static boolean isEmpty(String s) {
        return s == null || s.length() == 0 || "".equals(s)
                || "null".equalsIgnoreCase(s)
                || "undefined".equalsIgnoreCase(s);
    }

}

